// +----------------------------------------------------------------------
// | CmsWing [ 美业管理系统 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016 psi All rights reserved.
// +----------------------------------------------------------------------
// | Author: huang <2374266244@qq.com>
// +----------------------------------------------------------------------
'use strict';
import Base from './base.js';

export default class extends Base {
  /**
   * index action
   * @return {Promise} []
   */
	
	async getmodelAction(){
		let pid = this.get('pid');
		let list = await this.model('or_rulemodel').where({pid:pid}).select();
		return this.json(list);
	}

	//编辑规则
	async editruleAction(){
		if(this.isPost){
			let data = this.post();
			let is_exist = await this.model('or_rulegroup').where({groupid:data.groupid,grouptype:data.grouptype}).find();
			let res;
			if(!think.isEmpty(is_exist)){
				data.id = is_exist.id;
				res = await this.model('or_rulegroup').where({id:data.id}).update(data);
			}else{
				res = await this.model('or_rulegroup').add(data);
			}
			return res?this.success({info:"操作成功！"}):this.fail('操作失败！');
		}

		let id = this.get('id');
		let grouptype = this.get('grouptype');
		let uinfo = await this.model('or_rulegroup').where({groupid:id,grouptype:grouptype}).find();

		//取出当前所有模块和规则集合
		let modelurl = await this.model('or_rulemodel').where({category:['IN',[1,2]]}).select();

		return this.json({
			mlist:modelurl,
			usermodellist:uinfo.modelarr || '{}',
		});
	}

	//杨长远要求的对象格式对象转数组函数
	arraytoobject(data,modelarr,urlarr){
		var newdata = {};
		if (data instanceof Array) {
			for (var i = data.length - 1; i >= 0; i--) {	
				if(data[i]['tags']){
					newdata[data[i]['tags']] = this.arraytoobject(data[i],modelarr,urlarr);
				}else if(data[i]['url']){
					newdata[data[i]['url']] = this.arraytoobject(data[i],modelarr,urlarr);
				}					
			};
			return newdata;
		}else if(data instanceof Object){
			if(!modelarr[data['tags']]){
				//data['select'] = true;
				data = null;
				//return data;
				//delete(data);
			}else{
				delete(data['name']);
				delete(data['pid']);
				delete(data['id']);
				
				/*if(urlarr[data['url']]){
					data['select'] = true;
				}*/
				delete(data['tags']);
				delete(data['url']);
				delete(data['urllist']);
				if (data['childlist'].length > 0) {
					for (var i = data['childlist'].length - 1; i >= 0; i--) {
						if(modelarr[data['childlist'][i].tags]){
							data[data['childlist'][i].tags] = true;
						}
					};
				};
				delete data['childlist'];
				return data;
			}

			
			/*for(var key in data){
				if(data[key] instanceof Array){
					data[key] = this.arraytoobject(data[key],modelarr,urlarr);
				}
			}*/
			
		}
		else{
			return data;
		}
	}

	// 获取权限管理
	async getruleAction(){
		let id = this.get('id');

		let rule = await this.model('or_rulemodel').where({category:["IN",[3,4]]}).select();

		let perm = await this.model('or_rule_admin').where({id: id}).getField('gradepermission', true);

		let list = {
			rule: rule,
			perm: perm
		}

		return this.json(list);
	}

	// 增加权限板块
	async addruleAction(){
		let rule = this.post();
		let data;
		if (rule.pid) {
			data = {
				name : rule.name,
				tags : rule.tags,
				category : rule.category,
				pid : rule.pid,
			}
			let res = await this.model('or_rulemodel').add(data);
			return res?this.success({info:'添加成功'}):this.fail('添加失败');
		}
		data = {
			name : rule.name,
			category : rule.category,
		}
		let res = await this.model('or_rulemodel').add(data)
		return res?this.success({info:'添加成功'}):this.fail('添加失败');
	}

	// 删除权限板块
	async deleteruleAction(){
		let delstr = JSON.parse(this.post('delarr'));

		let delpermisstionarr = [], delMiss = [];
		for (var i = 0, delstrLen = delstr.length; i < delstrLen; i++) {
			delpermisstionarr.push(await this.model('or_rulemodel').where({category:2,pid:delstr[i]}).getField('id'));
		}
		if (!think.isEmpty(delpermisstionarr)) {
			for (var i = 0, permissionLen = delpermisstionarr.length; i < permissionLen; i++) {
				delMiss = delMiss.concat(delpermisstionarr[i]);
			}
		}
		
		let model = this.model('or_rulemodel');
		await model.transaction(async ()=>{
			try {
				let dm = 1,dl = 1;
				if (!think.isEmpty(delMiss)) {
					for (var i = 0, missLen = delMiss.length; i < missLen; i++) {
						dm = await model.where({id:delMiss[i]}).db(model.db()).delete();
					}
				}

				for (var i = 0, arrLen = delstr.length; i < arrLen; i++) {
					dl = await model.where({id:delstr[i]}).db(model.db()).delete();
				}

				if (dm&&dl) {
					model.commit();
					return this.success({info:'删除成功'});
				}
			} catch(e) {
				console.log(e);
				model.rollback();
				return this.fail('删除失败');
			}
		})
	}

	// 删除权限功能
	async deletepermissionAction(){
		let delarr = JSON.parse(this.post('delarr'));
		let res = await this.model('or_rulemodel').where({id:['IN',delarr]}).delete();
		return res?this.success({info:'删除成功'}):this.fail('删除失败');
	}

	// 取出管理组的等级分配(店家总管理员[特定等级])
	async getgradeallotAction(){
		let type = this.get('type');
		let orid = this.userinfo.departmentid;
		if (type) {
			let data = await this.model('or_rule_admin').where({departmentid: orid}).order('gradeid ASC').select();
			return this.json(data);
		} else {
			let data = await this.model('or_rule_admin').where({id:2}).select();
			return this.json(data);
		}
		
	}

	// 新增其他权限
	async addotherpermissionAction(){

		let data = this.post();
		let orid = this.userinfo.departmentid;
		let time = Math.round(new Date().valueOf()/1000);

		if (data.id*1) {

			let chongfu = await this.model('or_rule_admin').where({gradeid:data.gradeid, departmentid:orid, id:['!=',data.id]}).find();
			if (!think.isEmpty(chongfu)) {
				return this.fail('添加权限等级不能重复');
			}
			let gengxin = await this.model('or_rule_admin').where({id: data.id}).update({gradeid: data.gradeid, remarks: data.remarks, edittime: time});
			return gengxin?this.success('更改成功'):this.fail('更改失败');
		}

		let leng = await this.model('or_rule_admin').where({departmentid: orid}).select();

		if (leng.length > 10) {
			return this.fail('增加的权限等级过多');
		}

		let isrepeat = await this.model('or_rule_admin').where({gradeid:data.gradeid,departmentid: orid}).find();
		if (!think.isEmpty(isrepeat)) {
			return this.fail('添加权限等级不能重复');
		}
		let addone = {
			gradeid: data.gradeid,
			gradepermission: '[]',
			remarks: data.remarks,
			edittime: time,
			departmentid: orid
		}

		let res = await this.model('or_rule_admin').add(addone);
		return res?this.success('添加成功'):this.fail('添加失败');
	}

	// 修改后台权限
	async editadminpermissionsAction(){
		let data = this.post();

		let res = await this.model('or_rule_admin').where({id: data.id}).update({
			gradepermission: data.pers,
			edittime: Math.round(Date.now()/1000)
		});

		return res ? this.success({info:'修改成功'}) : this.fail('修改失败');
	}

	// 删除其他权限
	async deleteothergradeAction(){
		let id = this.post('id');
		let orid = this.userinfo.departmentid;
		let isuse = await this.model('or_admin').where({departmentid: orid, groupid: id}).select();
		if (!think.isEmpty(isuse)) {
			return this.fail('当前权限已经被使用');
		}
		let res = await this.model('or_rule_admin').where({id:id}).delete();
		return res?this.success('删除成功'):this.fail('删除失败');
	}

	// 设置店家账户权限
	async shopselectgradeAction(){
		let data = this.post();

		let res = await this.model('or_admin').where({id:data.id}).update({groupid:data.groupid});
		return res?this.success('修改成功'):this.fail('修改失败');
	}

	// 设置门店权限
	async getallshopAction(){
		let id = this.post('id');
		// 获取当前机构下的所有分店
		let floors = await this.model('or_department').where({pid:this.userinfo.departmentid,floor:1,isdisable:0}).select();
		// 获取当前机构下有权限的分店Id
		let ans = await this.model('or_rulegroup').where({groupid:id}).find();
		let frule;
		if (!think.isEmpty(ans)) {
			frule = ans.jsonshop;
		}

		let data = {
			floor : floors,
			frule : frule
		}
		return this.json(data);
	}

	async setfloorruleAction(){
		let info = this.post();
		let rulegroup = this.model('or_rulegroup');
		let isEm = await rulegroup.where({groupid:info.id}).find();
		if (!think.isEmpty(isEm)) {
			let res = await rulegroup.where({groupid:info.id}).update({jsonshop:info.floors});
			return res?this.success({info:'修改成功'}):this.fail('修改失败');
		}
		let data = {
			grouptype : info.grouptype,
			groupid : info.id,
			jsonshop : info.floors
		}
		let res = await rulegroup.add(data)
		return res?this.success({info:'添加成功'}):this.fail('添加失败');
	}

}